package first.niuke.midding;

/**
 * @ClassName NC77
 * @description:
 * @author: 荣燊
 * @create: 2021-06-20 15:03
 **/
public class NC77 {
    public static void main(String[] args) {
        //
        int[] arr = {2, 4, 6, 5, 7};
        for (int a : reOrderArray2(arr)) {
            System.out.println(a);
        }
    }

    // 调整数组顺序使奇数位于偶数前面
    public static int[] reOrderArray (int[] array) {
        // write code here
        int index = 0;
        int[] res = new int[array.length];
        for (int i : array) {
            if (i % 2 != 0) {
                res[index] = i;
                index++;
            }
        }
        for (int i : array) {
            if (i % 2 == 0) {
                res[index] = i;
                index++;
            }
        }
        return res;
    }

    // 并不能保证奇数和奇数，偶数和偶数之间的相对位置不变
    public static int[] reOrderArray1 (int[] array) {
        // write code here
        int i = 0, j = array.length - 1;
        while (i < j) {
            while (i < j && array[i] % 2 == 1) {
                i++;
            }
            while (i < j && array[j] % 2 == 0) {
                j--;
            }
            int tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;
        }

        return array;
    }

    // 维持数组的先后顺序，使用冒泡排序.时间复杂度大
    public static int[] reOrderArray2 (int[] array) {
        // write code here
        if (array == null || array.length == 0) {
            return array;
        }

        for (int j=0; j<array.length; j++) {
            for (int i=0; i<array.length-j-1; i++) {
                if (array[i] % 2 == 0 && array[i+1] % 2 == 1) {
                    int tmp = array[i];
                    array[i] = array[i+1];
                    array[i+1] = tmp;
                }
            }
        }
        return array;
    }
}
